package com.lee.commonerror.code.lock;

import com.lee.commonerror.common.annotation.Right;
import com.lee.commonerror.common.annotation.Wrong;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author ：liylw
 * @date ：Created in 2021/4/12 17:20
 */
@Wrong("锁的粒度问题")
@Slf4j
public class LockScopeWrong {

    private List<Integer> data = new ArrayList<>();

    /**
     * 不涉及共享资源的慢方法
     */
    private void slow() {
        try {
            TimeUnit.MILLISECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Wrong("锁的粒度过大")
    private int wrong() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        IntStream.rangeClosed(1, 1000).parallel().forEach(i -> {
            synchronized (this) {
                slow();
                data.add(i);
            }
        });
        stopWatch.stop();
        log.info(stopWatch.prettyPrint());
        return data.size();
    }

    @Right
    private int right() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        IntStream.rangeClosed(1, 1000).parallel().forEach(i -> {
            slow();
            synchronized (this) {
                data.add(i);
            }
        });
        stopWatch.stop();
        log.info(stopWatch.prettyPrint());
        return data.size();
    }

    public static void main(String[] args) {
        LockScopeWrong lockScopeWrong = new LockScopeWrong();
        lockScopeWrong.wrong();
        lockScopeWrong.right();

    }

}
